package serverx

import (
	"fmt"
	"io"

	"gitee.com/workits/pkgs/logx"
	"github.com/gin-gonic/gin"
	"github.com/go-playground/validator/v10"
	swaggerFiles "github.com/swaggo/files"
	ginSwagger "github.com/swaggo/gin-swagger"
)

// Validator 参数校验工具
var Validator *validator.Validate

func Run(mode string, cfg Config, initRoutes func(engine *gin.Engine)) {
	gin.SetMode(mode)
	gin.DefaultWriter = io.Discard // 屏蔽gin日志
	engine := gin.New()
	if err := engine.SetTrustedProxies(nil); err != nil {
		panic(err)
	}

	// 加载中间件
	engine.Use(gin.Recovery()) // 容错
	if cfg.CorsHeaders != nil && len(cfg.CorsHeaders) > 0 {
		engine.Use(WithCors(cfg.CorsHeaders...)) // 跨域
	}
	engine.Use(WithTraceid())   // 链路追踪
	engine.Use(WithAccesslog()) // 访问日志

	Validator = validator.New() // 启动前先初始化校验工具
	initRoutes(engine)          // 加载路由

	// 集成swagger ui
	if gin.Mode() != gin.ReleaseMode && len(cfg.SwaggerUI) > 0 {
		engine.GET(fmt.Sprintf("%s/*any", cfg.SwaggerUI), ginSwagger.WrapHandler(swaggerFiles.Handler))
	}

	// 异步启动服务
	go func() {
		logx.Fatalf(engine.Run(cfg.Addr).Error())
	}()
}
